<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Schema;

class StationController extends Controller
{
    //设备数据对照
    public function upParam(){
        $data = DB::table('station_up_param')->orderBy('param_name','asc')->get();
        if (request()->expectsJson()  || request('from_controller')) {
            if(request()->isMethod('post')){ //添加、编辑
                $reqData = request()->only('station_name','param','param_name');
                if($id = request('id')){
                    $res = DB::table('station_up_param')->where('id',$id)->update($reqData);
                }else{
                    $exists = DB::table('station_up_param')->where(['station_name'=>$reqData['station_name'],'param'=>$reqData['param']])->exists();
                    if($exists){
                        return out(0,'参数已存在！');
                    }
                    $res = DB::table('station_up_param')->insertGetId($reqData);
                }
                return $res;
            }
            $res = [];
            foreach($data as $item){
                if($item->param_name){
                    $res[$item->station_name][] = $item;
                }
            }
            return response()->json($res);
        }
        return view('admin.station.upParam',compact('data'));
    }
    public static function dbStat() {
        $data = [
            'trace_type'  => [
                1 => '检定',
                2 => '校准',
                3 => '核查',
            ],
            'status'      => [
                1 => '合格',
                2 => '准用',
                3 => '停用',
                4 => '淘汰',
            ],
            'trace_cycle' => [
                //溯源周期key是几个月
                0  => '/',
                6  => '半年',
                12 => '一年',
                24 => '两年',
            ]
        ];
        return $data;
    }

    //工位 列表展示
    public function index(Request $request) {
        if($request->expectsJson()) {
            //ajax请求
            //工位 列表 datatable的ajax 加载
            $data = DB::table('a_station')->orderBy('dev_num','asc')->get();
            $jsonData['data'] = $data;
            return response()->json($jsonData);
        }
        else {
            $data = self::dbStat();
            return view('admin.station.index', compact('data'));
        }
    }

    //工位 删除
    public function del(Request $request) {
        $id = $request->id;
        //  delete 返回受影响的行数
        $result = DB::table('a_station')->where('id', $id)->delete();
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $result >= 0 ? '1' : '0';
    }

    //工位 添加
    public function add(Request $request) {
        if($request->isMethod('POST')) {
            $post_data = $request->except(['_token','_form_token']);

            if(DB::table('a_station')->where('dev_num', $post_data['dev_num'])->exists()) {
                return '编码重复！';
            }
            $post_data = $this->editPostData($post_data);
            $result = DB::table('a_station')->insert($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '0';
        }
        else {
            $data = self::dbStat();
            $data['parents'] = $this->getPar();
            return view('admin.station.add', compact('data'));
        }
    }

    //工位 修改
    public function edit(Request $request) {
        $id = $request->id;
        if($request->isMethod('POST')) {
            $post_data = $request->except(['_token','_form_token']);
            $where = [['id', '!=', $id], ['dev_num', '=', $post_data['dev_num']]];
            if(DB::table('a_station')->where($where)->exists()) {
                return '编码/设备编号已存在';
            }
            $post_data = $this->editPostData($post_data);
            $result = DB::table('a_station')->where('id', $id)->update($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '还没修改数据！';
        }
        else {
            //查询要修改的工位 信息
            $info = DB::table('a_station')->find($id);
            $data = self::dbStat();
            $data['parents'] = $this->getPar();
            $data['pnum'] = $info->pid == 0 ? '/' : (DB::table('a_station')->where('id',$info->pid)->value('dev_num'));
            return view('admin.station.edit', compact('info', 'data'));
        }
    }

    private function editPostData($data) {
        $data['trace_exp_date'] = $data['trace_cycle'] ? date('Y-m-d', strtotime("+{$data['trace_cycle']} months -1 days", strtotime($data['trace_date']))) : ''; //计算溯源到期日期

        if(!$data['buy_date']){
            unset($data['buy_date']);
        }
        if (!$data['trace_date']) {
            unset($data['trace_date']);
            unset($data['trace_exp_date']);
        }
        if ($data['trace_cycle'] == 0) {
            unset($data['trace_exp_date']);
        }

        $data['pid'] = $data['pid'] == '/' ? 0 : (DB::table('a_station')->where('dev_num',$data['pid'])->value('id'));

        // $data = array_filter($data);     //去掉为空的数据
        return $data;
    }

    //获取pid为0的数据
    private function getPar() {
        $parents = DB::table('a_station')->where('pid', 0)->select('name', 'dev_num')->orderBy('dev_num','desc')->get()->toArray();
        $p0 = [
            'name'    => '作为顶级设备',
            'dev_num' => '/'
        ];
        $parents[] = (object)$p0;
        $parents = array_reverse($parents);
        return $parents;
    }
}
